<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
    <link rel="stylesheet" href="../utils/bootstrap-5.3.3-dist/css/bootstrap.min.css">
    <script src="../utils/bootstrap-5.3.3-dist/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="../utils/icon/iconfont.css">
    <link rel="stylesheet" href="../css/shared.css">
    <style>
        /*中部布局*/
        .central-layout {
            display: grid;
            grid-template-rows: 70px 470px 50px;
            width: 80vw;
            margin: 0 auto;
        }

        /*弹窗中部布局*/
        .dialog-body-layout {
            display: grid;
            grid-template-rows: auto auto auto auto auto;
        }

        .table td {
            max-width: 20vw;
        }
    </style>
</head>
<body>
<div class="body-grid">
    <!--头部-->
    <div class="header-grid">
        <!--    返回按钮-->
        <div>
            <!--        <button class="btn btn-secondary iconfont go-back-button">&#xe623;</button>-->
        </div>
        <!--    标题-->
        <div class="page-title">
            ARDF管理系统--新增赛事
        </div>
        <div></div>
    </div>
    <!--中部-->
    <div class="central-layout">
        <div>
            <button class="btn btn-danger" style="float: left;margin-top: 15px;" onclick="openDialog('delete-dialog')">
                批量删除
            </button>
            <button id="add-competition-pop" type="button" class="btn btn-primary"
                    style="float: right;margin-top: 15px;"
                    onclick="openDialogWithTitle('competition-dialog','新增赛事')">
                新增赛事
            </button>
            <!--            弹窗-->
            <div id="competition-dialog" class="my-dialog" style="display: none">
                <div class="my-dialog-header">
                    <!--                    标题占位-->
                    <span></span>
                    <button type="button" class="btn-close close-icon"
                            onclick="cancelCompetitionDialog('competition-dialog')"></button>
                </div>
                <div class="my-dialog-body  dialog-body-layout">
                    <div class="input-layout">
                        <div class="label-area">
                            <label for="competition-name">赛事名称<span style="color:red;">*</span>：</label>
                        </div>
                        <div class="input-area">
                            <input type="text" id="competition-name" name="name" style="width: 100%">
                        </div>
                        <div class="err-area">
                            <!--                      请输入赛事名称！/长度不大于30字      -->
                            <small style="color: red;"></small>
                        </div>
                    </div>
                    <div class="input-layout">
                        <div class="label-area">
                            <label for="competition-place">比赛地点<span style="color:red;">*</span>：</label>
                        </div>
                        <div class="input-area">
                            <input type="text" id="competition-place" name="place" style="width: 100%">
                        </div>
                        <div class="err-area">
                            <!--                            长度不大于30字！-->
                            <small style="color: red;"></small>
                        </div>
                    </div>
                    <div class="input-layout">
                        <div class="label-area">
                            <label for="competition-start-time">开始时间<span style="color:red;">*</span>：</label>
                        </div>
                        <div class="input-area">
                            <input type="date" id="competition-start-time" name="startTime">
                        </div>
                        <div class="err-area">
                            <!--                            开始时间应大于当前时间！-->
                            <small style="color: red;"></small>
                        </div>
                    </div>
                    <div class="input-layout">
                        <div class="label-area">
                            <label for="competition-end-time">结束时间<span style="color:red;">*</span>：</label>
                        </div>
                        <div class="input-area">
                            <input type="date" id="competition-end-time" name="endTime">
                        </div>
                        <div class="err-area">
                            <!--                            结束时间应大于开始时间！-->
                            <small style="color: red;"></small>
                        </div>
                    </div>
                    <div class="input-layout">
                        <div class="label-area">
                            <label for="competition-organization">主办单位<span style="color:red;">*</span>：</label>
                        </div>
                        
                        <div class="input-area">
                            <input type="text" id="competition-organization" name="organization" style="width: 100%">
                        </div>
                        <div class="err-area">
                            <!--                            长度不大于16字！-->
                            <small style="color: red;"></small>
                        </div>
                    </div>
                </div>

                <div class="my-dialog-footer">
                    <button type="button" class="btn btn-secondary btn-sm my-dialog-ft-btn"
                            onclick="cancelCompetitionDialog('competition-dialog')">取消
                    </button>
                    <button type="button" class="btn btn-primary btn-sm my-dialog-ft-btn"
                            onclick="submitCompetitionDialog('competition-dialog')">确认
                    </button>
                </div>
            </div>
        </div>
        <!--    表格-->
        <div class="table-responsive">
            <table id="competition-table" class="table table-sm table-bordered text-center">
                <thead>
                <tr>
                    <th>
                        <label>
                            全选
                            <input type="checkbox" onclick="selectMul('competition-table')">
                        </label>
                    </th>
                    <th>比赛名称</th>
                    <th>主办方</th>
                    <th>比赛时间</th>
                    <th>比赛地点</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="table-records" class="table-group-divider">
                   
                </tbody>
            </table>
        </div>
        <div>

            <!--    分页组件-->
            <ul class="pagination page-ul-flex" id="pagination">

            </ul>
        </div>


    </div>
    <!--尾部-->
    <div class="footer-grid">
        <!--网格留空-->
        <div></div>
        <!--进度条-->
        <div id="progress-bar" class="progress-bar-flex">
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button"></button>
                <div class="progress-bar-text">新增赛事</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">新增项目</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">设置组别</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">导入选手</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">下发号码</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">制卡</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">签到</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">批次管理</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">规则设置</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">开始比赛</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">成绩计算</div>
                <i class="iconfont progress-bar-arrow" style="visibility: hidden;">&#xe604;</i>
            </div>
        </div>
        <!--    网格留空-->
        <div></div>
    </div>
</div>
<!--删除弹窗-->
<div id="delete-dialog" class="my-dialog my-dialog-smaller" style="display: none">
    <div class="my-dialog-header">
        <!--                    标题占位-->
        <span>确定要批量删除吗？</span>
        <button type="button" class="btn-close close-icon"
                onclick="closeDialog('delete-dialog')"></button>
    </div>
    <div class="my-dialog-body">
    </div>
    <div class="my-dialog-footer">
        <button type="button" class="btn btn-secondary btn-sm my-dialog-ft-btn"
                onclick="closeDialog('delete-dialog')">取消
        </button>
        <button type="button" class="btn btn-primary btn-sm my-dialog-ft-btn"
                onclick="deleteBatch('competition-table','delete-dialog')">确认
        </button>
    </div>
</div>
<script src="../js/pages.js"></script>
<script src="../api/urls.js"></script>
<script src="../js/dialog.js"></script>
<script src="../js/progress.js"></script>
<script>
    //页码
    let pageNum = 1;
    //一页多少条
    let pageSize = 9;
    //总条数
    let total;
    //总页数
    let pages;
    //请求记录
    let records;
    //更新id
    let updateId;

    /**
     * 渲染表格
     */
    function drawCompetitionTable(records) {
        let mulSelect = document.querySelector("#competition-table thead input");
        mulSelect.checked = false;
        let tableBody = document.getElementById("table-records");
        tableBody.innerHTML = "";
        for (let record of records) {
            let trElement = document.createElement("tr");
            trElement.dataset.competitionId = record.id;
            let tdElement1 = document.createElement("td");
            let inputElement = document.createElement("input");
            inputElement.type = "checkbox";
            tdElement1.append(inputElement);
            let tdElement2 = document.createElement("td");
            tdElement2.textContent = record.name;

            let tdElementO = document.createElement("td");
            tdElementO.textContent = record.organization;

            let tdElement3 = document.createElement("td");
            if (record.startTime && record.endTime) {
                tdElement3.textContent = record.startTime.split("T")[0] + "——" +
                    record.endTime.split("T")[0];
            } else if (record.startTime) {
                tdElement3.textContent = record.startTime.split("T")[0] + "——"
            } else if (record.endTime) {
                tdElement3.textContent = "——" + record.endTime.split("T")[0];
            }
            let tdElement4 = document.createElement("td");
            tdElement4.textContent = record.place;
            let tdElement5 = document.createElement("td");
            let buttonElement1 = document.createElement("button");
            buttonElement1.classList.add("btn", "btn-primary", "btn-sm", "iconfont");
            buttonElement1.style.marginRight = "10px";
            buttonElement1.textContent = "\u{e6f7}编辑";
            buttonElement1.addEventListener("click", () => {
                let inputs = document.querySelectorAll("#competition-dialog .input-area");
                inputs[0].firstElementChild.value = record.name;
                inputs[1].firstElementChild.value = record.place;
                if (record.startTime) {
                    inputs[2].firstElementChild.value = record.startTime.split("T")[0];
                }
                if (record.endTime) {
                    inputs[3].firstElementChild.value = record.endTime.split("T")[0];
                }
                inputs[4].firstElementChild.value = record.organization;
                updateId = record.id;
                openDialogWithTitle('competition-dialog', '编辑赛事');
            });
            let buttonElement2 = document.createElement("button");
            buttonElement2.classList.add("btn", "btn-primary", "btn-sm", "iconfont");
            buttonElement2.textContent = "\u{e61f}进入赛事";
            buttonElement2.addEventListener("click", () => {
                window.sessionStorage.setItem("competitionId", String(record.id));
                window.sessionStorage.setItem("competitionName", String(record.name));
                window.sessionStorage.setItem("competitionTime", String(record.startTime));
                window.sessionStorage.setItem("competitionEndTime", String(record.endTime));
                window.sessionStorage.setItem("progress", String(record.progress));
                switch (record.progress) {
                    case PROJECT_PROGRESS:
                        window.location.href = "project.html";
                        break;
                    case GROUP_PROGRESS:
                        window.location.href = "group.html";
                        break;
                    case ATHLETE_PROGRESS:
                        window.location.href = "athlete.html";
                        break;
                    case NUMBER_PROGRESS:
                        window.location.href = "number.html";
                        break;
                    case CARD_ISSUANCE_PROGRESS:
                        window.location.href = "card-issuance.html";
                        break;
                    case SIGN_IN_PROGRESS:
                        window.location.href = "sign-in.html";
                        break;
                    case BATCH_PROGRESS:
                        window.location.href = "batch.html";
                        break;
                    default:
                        console.log("跳转错误");
                        break;
                }
            });
            tdElement5.append(buttonElement1, buttonElement2);
            trElement.append(tdElement1, tdElement2,tdElementO, tdElement3, tdElement4, tdElement5);
            tableBody.append(trElement);
        }
    }


    //实现分页的方法
    async function getPage(pageNum, pageSize) {
        let url = new URL(COMPETITION_URL + PAGE_URL);
        url.searchParams.set("pageNum", pageNum);
        url.searchParams.set("pageSize", pageSize);
        await fetch(url).then(response => {
            if (response.ok && response.headers.get("Content-Type") === "application/json") {
                return response.json();
            } else {
                throw new Error(`未知相应状态 ${response.status}或Content-Type：${response.headers.get("Content-Type")}`);
            }
        }).then(pageInfo => {
            pages = pageInfo.pages;
            total = pageInfo.total;
            records = pageInfo.records;
            drawCompetitionTable(records);
        }).catch(error => {
            console.log("赛事分页错误：", error);
        });
    }

    //上一页
    async function prePage() {
        pageNum = pageNum - 1;
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);
    }

    //下一页
    async function nextPage() {
        pageNum = pageNum + 1;
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages)
    }

    //点击切换
    async function handlePage(page) {
        if (page !== pageNum) {
            pageNum = page
            await getPage(pageNum, pageSize);
            createpage(pageNum, pageSize, total, pages);
        }

    }

    // 创建分页组件
    async function showPage() {
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);
    }

    showPage();

    /**
     * 取消弹窗
     * @param dialogId
     */
    function cancelCompetitionDialog(dialogId) {
        let inputs = document.querySelectorAll("#" + dialogId + " .input-area");
        let errs = document.querySelectorAll("#" + dialogId + " .err-area");
        for (let input of inputs) {
            input.firstElementChild.value = null;
        }
        for (let err of errs) {
            err.firstElementChild.textContent = "";
        }
        closeDialog(dialogId);
    }

    /**
     * 校验数据
     * @param dialogId
     * @returns {boolean}
     */
    function verifyForm(dialogId) {
        let flag = true;
        let inputs = document.querySelectorAll("#" + dialogId + " .input-area");
        for (let input of inputs) {
            let name = input.firstElementChild.name;
            let value = input.firstElementChild.value ? input.firstElementChild.value.trim() : null;
            if (input.nextElementSibling) {
                input.nextElementSibling.firstElementChild.textContent = "";
            }
            if (name === "name") {
                if (!value || value === "") {
                    input.nextElementSibling.firstElementChild.textContent = "赛事名称不能为空！";
                    flag = false;
                } else if (value && value.length > 30) {
                    input.nextElementSibling.firstElementChild.textContent = "长度不大于30字！";
                    flag = false;
                }

            }else if (name === "organization") {
                if (!value || value === "") {
                    input.nextElementSibling.firstElementChild.textContent = "主办方不能为空！";
                    flag = false;
                } else if (value && value.length > 16) {
                    input.nextElementSibling.firstElementChild.textContent = "长度不大于16字！";
                    flag = false;
                }

            } else if (name === "place") {
                if (!value || value === "") {
                    input.nextElementSibling.firstElementChild.textContent = "比赛地点不能为空！";
                    flag = false;
                }
                if (value && value.length > 30) {
                    input.nextElementSibling.firstElementChild.textContent = "长度不大于30字！";
                    flag = false;
                }
            } else if (name === "startTime") {
                if (value) {
                    let date = new Date(value);
                    let dateNow = new Date();
                    if (date < dateNow) {
                        input.nextElementSibling.firstElementChild.textContent = "开始时间应大于当前时间！";
                        flag = false;
                    }
                }else{
                    input.nextElementSibling.firstElementChild.textContent = "开始时间不能为空！";
                    flag = false;
                }
            } else if (name === "endTime") {
                if (value && value !== "") {
                    let endDate = new Date(value);
                    let dateNow = new Date();
                    if (endDate < dateNow) {
                        input.nextElementSibling.firstElementChild.textContent = "结束时间应大于当前时间！";
                        flag = false;
                    }
                    let startTimeValue = input.parentElement.previousElementSibling.children[1].firstElementChild.value;
                    if (startTimeValue && startTimeValue !== "") {
                        let startDate = new Date(startTimeValue);
                        if (endDate < startDate) {
                            input.nextElementSibling.firstElementChild.textContent = "结束时间应大于开始时间！";
                            flag = false;
                        }

                    }
                }else{
                    input.nextElementSibling.firstElementChild.textContent = "结束时间不能为空！";
                    flag = false;
                }

            }
        }
        return flag;
    }

    /**
     * 提交弹窗
     * @param dialogId
     */
    async function submitCompetitionDialog(dialogId) {
        if (!verifyForm(dialogId)) {
            return;
        }
        let bodyMap = new Map();
        let inputs = document.querySelectorAll("#" + dialogId + " .input-area");
        let errs = document.querySelectorAll("#" + dialogId + " .err-area");
        for (let input of inputs) {
            if (input.firstElementChild.value === "") {
                bodyMap.set(input.firstElementChild.name, null);
            } else if (input.firstElementChild.value) {
                bodyMap.set(input.firstElementChild.name, input.firstElementChild.value.trim())
            } else {
                bodyMap.set(input.firstElementChild.name, null);
            }
            input.firstElementChild.value = null;
        }
        for (let err of errs) {
            err.firstElementChild.textContent = "";
        }
        closeDialog(dialogId);
        let url;
        if (document.querySelector("#" + dialogId + ">.my-dialog-header>span").textContent === "新增赛事") {
            bodyMap.set("progress", 0);
            url = new URL(COMPETITION_URL + ADD_URL);
        } else {
            bodyMap.set("id", updateId);
            url = new URL(COMPETITION_URL + UPDATE_URL);
        }
        let bodyObject = Object.fromEntries(bodyMap);
        await fetch(url, {
            method: "POST",
            headers: new Headers({"Content-Type": "application/json"}),
            body: JSON.stringify(bodyObject)
        });
        await showPage();
    }

    /**
     * 多选框实现
     */
    function selectMul(tableId) {
        let mulSelect = document.querySelector("#" + tableId + " thead input");
        let trs = document.querySelectorAll("#" + tableId + " tbody>tr");
        for (let tr of trs) {
            tr.firstElementChild.firstElementChild.checked = mulSelect.checked;
        }
    }

    async function deleteBatch(tableId, dialogId) {
        let deleteIds = [];
        let trs = document.querySelectorAll("#" + tableId + " tbody>tr");
        for (let tr of trs) {
            if (tr.firstElementChild.firstElementChild.checked) {
                deleteIds.push(Number(tr.dataset.competitionId));
            }
        }
        closeDialog(dialogId);
        if (deleteIds.length !== 0) {
            await fetch(COMPETITION_URL + DELETE_BATCH_URL, {
                method: "POST",
                headers: new Headers({"Content-Type": "application/json"}),
                body: JSON.stringify(deleteIds)
            });
            await showPage();
        }
    }
    /**
     * 改变每页条数
     */
    async function changePageSize(value) {
        pageSize=Number(value);
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);
    }

</script>
</body>
</html>